package cn.tedu.straw.api.controller;


import cn.tedu.straw.api.dto.PostAnswerDTO;
import cn.tedu.straw.api.ex.ParameterValidationException;
import cn.tedu.straw.api.message.PostAnswerMessage;
import cn.tedu.straw.api.service.IAnswerService;
import cn.tedu.straw.commons.security.LoginUserInfo;
import cn.tedu.straw.commons.vo.AnswerVO;
import cn.tedu.straw.commons.vo.R;
import com.google.gson.Gson;
import org.apache.kafka.common.protocol.types.Field;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2020-08-11
 */
@RestController
@RequestMapping("/v1/answers")
public class AnswerController {

    @Autowired
    private IAnswerService answerService;
    @Autowired
    private Gson gson;
    @Autowired(required = false)
    private KafkaTemplate<String, String> kafkaTemplate;

    // http://localhost/api/v1/answers/post?questionId=7&content=Answer7
    // http://localhost:8080/v1/answers/post?questionId=7&content=Answer7
    @RequestMapping("/post")
    public R<Void> post(@Valid PostAnswerDTO postAnswerDTO,
                        BindingResult bindingResult,
                        @AuthenticationPrincipal LoginUserInfo loginUserInfo) {
        System.err.println("AnswerController.post");
        if (bindingResult.hasErrors()) {
            String message = bindingResult.getFieldError().getDefaultMessage();
            throw new ParameterValidationException(message);
        }
        // answerService.post(postAnswerDTO, loginUserInfo.getId(), loginUserInfo.getNickname());
        PostAnswerMessage postAnswerMessage = new PostAnswerMessage()
                .setPostAnswerDTO(postAnswerDTO)
                .setUserId(loginUserInfo.getId())
                .setUserNickName(loginUserInfo.getNickname());
        String message = gson.toJson(postAnswerMessage);
        kafkaTemplate.send("POST_ANSWER", message);
        return R.ok();
    }

    // http://localhost/api/v1/answers?questionId=10
    // http://localhost:8080/v1/answers?questionId=10
    @GetMapping({"", "/"})
    public R<List<AnswerVO>> getAnswerList(Integer questionId) {
        List<AnswerVO> answers = answerService.getAnswerList(questionId);
        return R.ok(answers);
    }

}
